<template>
  <el-dialog title="选择网点" v-model="visible" width="800px" append-to-body draggable :before-close="handleClose">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="网点编号" prop="bankCode">
        <el-input v-model="queryParams.bankCode" placeholder="请输入网点编号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="网点名称" prop="bankName">
        <el-input v-model="queryParams.bankName" placeholder="请输入网点名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="bankList" @selection-change="handleSelectionChange"
      @row-dblclick="handleRowDbClick" ref="tableRef">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" width="55" align="center" prop="id" />
      <el-table-column label="网点编号" align="center" prop="bankCode" />
      <el-table-column label="网点名称" align="center" prop="bankName" width="280px" />
      <el-table-column label="所属机构" align="center" prop="parentOrgName" width="200px" />
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="handlePageChange" small
      layout="total, sizes, prev, pager, next, jumper" />

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleConfirm">确 认</el-button>
        <el-button @click="handleCancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { listBank } from "@/api/service/bank"
import { handleSingleSelection, allOrganizations, getOrganizationList, getParentOrgName, handleSelectionHighlight } from "@/api/common"

/** 父页面传入的参数 */
const props = defineProps({
  // v-model
  modelValue: {
    type: Boolean,
    default: false
  },
  // 父页面传中来的参数
  bankId: {
    type: Number,
    default: null
  }
})

const emit = defineEmits(['update:modelValue', 'select'])

// 定义响应式数据
const queryRef = ref(null)
const tableRef = ref(null)
const loading = ref(false)
const showSearch = ref(true)
const total = ref(0)

const visible = computed({
  get() {
    return props.modelValue
  },
  set(value) {
    emit('update:modelValue', value)
  }
})

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  bankCode: undefined,
  bankName: undefined
})

const bankList = ref([])
const currentSelected = ref({})

// 监听visible变化，当对话框打开时加载数据
watch(visible, (newVal) => {
  if (newVal) {
    getList()
    // 父页面bankId，则根据ID查找并设置为当前选中项
    if (props.bankId) {
      const selectedBank = bankList.value.find(item => item.id === props.bankId)
      if (selectedBank) {
        currentSelected.value = selectedBank
      }
    }
  } else {
    // 关闭时重置选择
    currentSelected.value = {}
  }
})

/** 查询网点列表， 画面初始化契机*/
function getList() {
  loading.value = true
  listBank(queryParams).then(response => {
    // 处理每条记录，根据orgId设置parentOrgName和subOrgName用于展示
    bankList.value = response.rows.map(item => {
      // 从allOrganizations中查找对应的机构信息
      const org = allOrganizations.value.find(org => org.id === item.orgId);
      if (org) {
        // 查找该机构对应的父机构信息
        const parentOrg = allOrganizations.value.find(pOrg => pOrg.id === org.parentOrgId);
        if (parentOrg) {
          // 父机构存在时，机构名称显示父机构名称，二级机构显示机构名称
          item.parentOrgName = parentOrg.orgName;
          item.subOrgName = org.orgName;
        } else {
          // 父机构不存在时，机构名称显示机构名称，没有二级机构
          item.parentOrgName = org.orgName;
          item.subOrgName = "";
        }
      } else {
        // 机构不存在时，机构名称和父机构名称都为空
        item.parentOrgName = "";
        item.subOrgName = "";
      }
      return item;
    });
    // bankList.value = response.rows
    total.value = response.total
    loading.value = false

    // 父页面传入的bankId，则根据ID查找并设置为当前选中项
    if (props.bankId) {
      const selectedBank = bankList.value.find(item => item.id === props.bankId)
      if (selectedBank) {
        currentSelected.value = selectedBank
      }
    }
    else {
      // 如果没有传入的bankId，则将当前选中项设置为空对象
      currentSelected.value = {}
    }

    // 数据更新后也要检查是否需要选中某行
    handleSelectionHighlight(tableRef, bankList.value, currentSelected.value)
  }).catch(error => {
    console.error('获取网点列表失败:', error)
    loading.value = false
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  if (queryRef.value) {
    queryRef.value.resetFields()
  }
  handleQuery()
}

/** 分页操作 */
function handlePageChange(page) {
  queryParams.pageNum = page.page
  queryParams.pageSize = page.limit
  getList()
}

/** 处理选择变化 */
function handleSelectionChange(selection) {
  // 复选框实现单选功能
  const result = handleSingleSelection(selection, tableRef.value)
  currentSelected.value = result.selectedItem || {}
}

/** 双击行 */
function handleRowDbClick(row) {
  currentSelected.value = row
  handleConfirm()
}

/** 确认选择 */
function handleConfirm() {
  if (Object.keys(currentSelected.value).length === 0) {
    // 显示提示信息
    alert('请先选择一条数据')
    return
  }

  emit('select', currentSelected.value)
  visible.value = false
}

/** 取消选择 */
function handleCancel() {
  visible.value = false
}

/** 关闭前处理 */
function handleClose() {
  visible.value = false
}

getOrganizationList()
</script>

<style scoped>
/* 可以添加一些样式 */
</style>